package com.irdstudio.apicenter.gateway.web.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import com.irdstudio.apicenter.gateway.comm.MaccsPacket;
import com.irdstudio.apicenter.gateway.web.MaccsException;
import com.irdstudio.apicenter.gateway.web.MaccsTradeDefineVo;
import com.irdstudio.apicenter.gateway.web.view.View;

/**
 * 组装参数发送给同盾
 * 
 * @author fmf
 *
 */
@Controller
public class AppSumbitTongdunInfo implements IController {
	/* 文本日志输出 */
	private static final Logger logger = LoggerFactory.getLogger(AppSumbitTongdunInfo.class);
	private HttpURLConnection TongdunConn;

	@Override
	public View execute(MaccsTradeDefineVo tradeDefine, MaccsPacket inPacket, HttpServletRequest request,
			HttpServletResponse response) throws MaccsException {
		// 1.接收app传入的参数

		// 2.信息发送给同盾

		return null;
	}

	public void sendMsgPost(String url, Map<String, String> map) {
		try {
			URL TongdunUrl = new URL(url);
			// 组织请求参数
			StringBuilder postBody = new StringBuilder();
			for (Map.Entry<String, String> entry : map.entrySet()) {
				if (entry.getValue() == null)
					continue;
				postBody.append(entry.getKey()).append("=")
						.append(URLEncoder.encode(entry.getValue().toString(), "utf-8")).append("&");
			}
			if (!map.isEmpty()) {
				postBody.deleteCharAt(postBody.length() - 1);
			}
			// 创建连接
			TongdunConn = (HttpURLConnection) TongdunUrl.openConnection();
			// 设置长链接
			TongdunConn.setRequestProperty("Connection", "Keep-Alive");
			TongdunConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			// 设置连接超时
			TongdunConn.setConnectTimeout(1000);
			// 设置读取超时
			TongdunConn.setReadTimeout(500);
			// 提交参数
			TongdunConn.setRequestMethod("POST");
			TongdunConn.setDoOutput(true);
			TongdunConn.getOutputStream().write(postBody.toString().getBytes());
			TongdunConn.getOutputStream().flush();
			int responseCode = TongdunConn.getResponseCode();
			if (responseCode != 200) {
				// 不成功
				return;
			}
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(TongdunConn.getInputStream(), "utf-8"));
			StringBuilder result = new StringBuilder();
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				result.append(line).append("\n");
			}
			System.out.println(result.toString());	
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (TongdunConn != null) {
				TongdunConn.disconnect();
			}
		}
	}
	
	
	
	

}
